package com.collins.io.nio.discard;

import com.collins.io.nio.config.Config;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

public class DiscardClient {
    private static final Logger logger = Logger.getLogger(DiscardClient.class);
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static AtomicInteger count = new AtomicInteger(0);
    private static final int PORT = Config.SERVER_PORT;
    private static final String HOST = "127.0.0.1";
    private static final int TIMES = 10;
    private static final int BUFFER_SIZE = 1024;

    public static void main(String[] args) throws IOException {
        for (int i = 0; i < TIMES; i++) {
            startClient(HOST,PORT);
        }
    }

    public static void startClient(String host, int port) throws IOException {
        InetSocketAddress address = new InetSocketAddress(host, port);
        // TODO 1 gain channel
        SocketChannel socketChannel = SocketChannel.open(address);
        socketChannel.configureBlocking(false);
        // TODO 2 spinning for connection establishment
        while (!socketChannel.finishConnect()) {}
        logger.info(sdf.format(new Date(System.currentTimeMillis()))
                + " connection success: " + host + ":" + port);
        // TODO 3 prepare data and send to server
        ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
        buffer.put(("hello! this is " + count.getAndIncrement() + " times!").getBytes());
        buffer.flip();
        socketChannel.write(buffer);
        socketChannel.shutdownOutput();
        socketChannel.close();
    }
}
